package com.android.gardensnake;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.TableLayout;

public class DbManager {
	TableLayout dataTable;
	
	public static final String KEY_ROWID = "_id";
	public static final String KEY_FNAME = "f_name";
	public static final String KEY_LNAME = "l_name";
	
	private static final String DATABASE_NAME = "namedb";
	private static final String DATABASE_TABLE = "peopletable";
	private static final int DATABASE_VERSION = 1;	
	
	private final Context ourContext;
	private DbHelper ourHelper;
	private SQLiteDatabase ourDatabase;
	
	private static class DbHelper extends SQLiteOpenHelper {		
		public DbHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
					KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
					KEY_FNAME + " TEXT NOT NULL, " + 
					KEY_LNAME + " TEXT NOT NULL" + ")" );
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
			onCreate(db);
		}
		
	}
	
	public DbManager(Context c) {
		ourContext = c;
	}

	public DbManager open() throws SQLException {
		ourHelper = new DbHelper(ourContext);
		ourDatabase = ourHelper.getWritableDatabase();
		return this;
	}

	public Long createEntry(String fName, String lName) throws SQLException {
		ContentValues cv = new ContentValues();
		cv.put(KEY_FNAME, fName);
		cv.put(KEY_LNAME, lName);
		return ourDatabase.insert(DATABASE_TABLE, null, cv);
	}

	public void close() {
		ourHelper.close();
	}

	public void deleteEntry(long lRowId) throws SQLException {
		ourDatabase.delete(DATABASE_TABLE, KEY_ROWID + " = " + lRowId, null);
	}

	public String getData() {
		String[] cloumns = new String[]{KEY_ROWID, KEY_FNAME, KEY_LNAME};
		Cursor c = ourDatabase.query(DATABASE_TABLE, cloumns, null, null, null, null, null);
		String result = "";
		int iRow = c.getColumnIndex(KEY_ROWID);
		int iFName = c.getColumnIndex(KEY_FNAME);
		int iLName = c.getColumnIndex(KEY_LNAME);
		for (c.moveToFirst() ; !c.isAfterLast(); c.moveToNext()) {
			result += c.getString(iRow) + "\t"
					+ c.getString(iFName) + "\t"
					+ c.getString(iLName) + "\n";
		}
		return result;
	}
}
